import { asyncRoutes, constantRoutes } from "@/router";
import { getRoutes } from "@/api/user.js";
import Layout from "@/layout";

const componentMap = {
  "@/views/BusinessManagement/BusinessList/BusinessList.vue": () =>
    import("@/views/BusinessManagement/BusinessList/BusinessList.vue"),
  "@/views/DeviceManagement/DeviceList/index.vue": () =>
    import("@/views/DeviceManagement/DeviceList/index.vue"),
  "@/views/DeviceManagement/GatewayList/index.vue": () =>
    import("@/views/DeviceManagement/GatewayList/index.vue"),
  "@/views/DeviceManagement/DevicePermissionList/index.vue": () =>
    import("@/views/DeviceManagement/DevicePermissionList/index.vue"),
  "@/views/DeviceManagement/WxDeviceList/index.vue": () =>
    import("@/views/DeviceManagement/WxDeviceList/index.vue"),
  "@/views/ProjectManagement/ProjectList.vue": () =>
    import("@/views/ProjectManagement/ProjectList.vue"),
  "@/views/DataManagement/EnergyconsumptionAnalysis/index.vue": () =>
    import("@/views/DataManagement/EnergyconsumptionAnalysis/index.vue"),
  "@/views/DataManagement/EnergyconsumptionComparison/index.vue": () =>
    import("@/views/DataManagement/EnergyconsumptionComparison/index.vue"),
  "@/views/GroupManagement/index.vue": () =>
    import("@/views/GroupManagement/index.vue"),
  "@/views/PersonalManagement/CorporateAdministrator/index.vue": () =>
    import("@/views/PersonalManagement/CorporateAdministrator/index.vue"),
  "@/views/PersonalManagement/ProjectManager/index.vue": () =>
    import("@/views/PersonalManagement/ProjectManager/index.vue"),
  "@/views/PersonalManagement/WeChatUser/index.vue": () =>
    import("@/views/PersonalManagement/WeChatUser/index.vue"),
  "@/views/MonitorManagement/OnlineUser/index.vue": () =>
    import("@/views/MonitorManagement/OnlineUser/index.vue"),
  "@/views/ScheduledtaskManagement/index.vue": () =>
    import("@/views/ScheduledtaskManagement/index.vue"),
  "@/views/SystemManagement/RoleManagement/index.vue": () =>
    import("@/views/SystemManagement/RoleManagement/index.vue"),
  "@/views/SystemManagement/MenuManagement/index.vue": () =>
    import("@/views/SystemManagement/MenuManagement/index.vue"),
  "@/views/SystemManagement/DictionaryManagement/index.vue": () =>
    import("@/views/SystemManagement/DictionaryManagement/index.vue"),
  "@/views/SystemManagement/ParamterManagement/index.vue": () =>
    import("@/views/SystemManagement/ParamterManagement/index.vue"),
  "@/views/SystemManagement/LogManagement/index.vue": () =>
    import("@/views/SystemManagement/LogManagement/index.vue"),
  "@/views/SystemManagement/LogManagement/ActionLog/index.vue": () =>
    import("@/views/SystemManagement/LogManagement/ActionLog/index.vue"),
  "@/views/SystemManagement/LogManagement/LoginLog/index.vue": () =>
    import("@/views/SystemManagement/LogManagement/LoginLog/index.vue"),
  "@/views/VersionManagement/index.vue": () =>
    import("@/views/VersionManagement/index.vue"),
  "@/views/MapModule/index.vue": () =>
    import("@/views/MapModule/index.vue"),
};
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  const routeRoles = route.roles || (route.meta && route.meta.roles);
  if (route.meta && route.meta.roles) {
    return roles.some((role) => route.meta.roles.includes(role));
  } else {
    return true;
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = [];

  routes.forEach((route) => {
    const tmp = { ...route };
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
      res.push(tmp);
    }
  });

  return res;
}

function convertApiRoutes(apiRoutes) {
  if (!Array.isArray(apiRoutes)) {
    console.warn("路由数据不是数组格式:", apiRoutes);
    return [];
  }

  return apiRoutes
    .map((route) => {
      // 处理组件
      let component;
      if (route.component) {
        // 特殊处理 Layout 组件
        if (["Layout", "@/layout", "@/Layout"].includes(route.component)) {
          component = Layout;
        } else {
          // 处理其他组件路径
          let componentPath = route.component;

          // 确保正确的文件扩展名
          if (!componentPath.match(/\.(vue|js|jsx|ts|tsx)$/)) {
            componentPath += ".vue";
          }

          if (componentMap[componentPath]) {
            component = componentMap[componentPath];
          }
        }
      }

      // 修复路径格式
      let routePath = route.path || "";
      // 处理双斜线问题
      if (routePath.startsWith("//")) {
        routePath = "/" + routePath.substring(2);
      }

      const convertedRoute = {
        path: routePath,
        name: route.name,
        component: component,
        meta: {
          title: route.title || route.meta?.title || "",
          icon: route.icon || route.meta?.icon || "",
        },
        hidden: route.hidden || false,
      };

      // 处理特殊字段
      if (route.redirect && route.redirect !== "noRedirect") {
        convertedRoute.redirect = route.redirect;
      }

      if (route.alwaysShow !== undefined) {
        convertedRoute.alwaysShow = route.alwaysShow;
      }

      // 过滤无效路由
      if (!convertedRoute.path && convertedRoute.path !== "/") {
        console.log("过滤掉无效路由:", convertedRoute);
        return null;
      }

      // 递归处理子路由
      if (route.children && route.children.length > 0) {
        convertedRoute.children = convertApiRoutes(route.children);
      }

      return convertedRoute;
    })
    .filter((route) => {
      const isValid = route !== null && (route.path || route.path === "/");
      return isValid;
    });
}

const state = {
  routes: [],
  addRoutes: [],
  isRoutesLoaded: false, // 添加一个标志位，标识路由是否已加载
  routesUpdated: false // 路由更新标志
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
    state.isRoutesLoaded = true;
  },
  RESET_ROUTES_STATE: (state) => {
    state.routes = [];
    state.addRoutes = [];
    state.isRoutesLoaded = false;
  },
  SET_ROUTES_UPDATED: (state, updated) => {
    state.routesUpdated = updated;
  },
};

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise((resolve) => {
      let accessedRoutes;
      if (roles.includes("admin")) {
        accessedRoutes = asyncRoutes || [];
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
      }
      commit("SET_ROUTES", accessedRoutes);
      resolve(accessedRoutes);
    });
  },

  // 后端接口返回的菜单列表
  generateRoutesFromAPI({ commit, state },userId) {
    // 如果路由已经加载过，直接返回已有的路由
    if (state.isRoutesLoaded) {
      return Promise.resolve(state.addRoutes);
    }
    return new Promise((resolve, reject) => {
      getRoutes({userId})
        .then((response) => {
          const { data } = response;

          if (!data) {
            console.warn("后端返回的菜单数据为空");
            commit("SET_ROUTES", []);
            resolve([]);
            return;
          };
          const accessedRoutes = convertApiRoutes(data);
          commit("SET_ROUTES", accessedRoutes);
          resolve(accessedRoutes);
        })
        .catch((error) => {
          console.error("获取菜单失败:", error);
          commit("RESET_ROUTES_STATE");
          reject(error);
        });
    });
  },
  // 重置路由状态
  resetRoutes({ commit }) {
    commit("RESET_ROUTES_STATE");
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
